package com.basic.backend.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.basic.backend.common.BaseResponse;
import com.basic.backend.common.DeleteRequest;
import com.basic.backend.common.ErrorCode;
import com.basic.backend.common.ResultUtils;
import com.basic.backend.constant.UserConstant;
import com.basic.backend.exception.BusinessException;
import com.basic.backend.exception.ThrowUtils;
import com.basic.backend.model.dto.user.*;
import com.basic.backend.model.dto.captcha.CaptchaInfo;
import com.basic.backend.model.entity.User;
import com.basic.backend.model.vo.LoginUserVO;
import com.basic.backend.model.vo.UserVO;
import com.basic.backend.service.UserService;
import com.basic.backend.utils.CaptchaGenerator;
import com.basic.backend.utils.CaptchaValidator;
import com.basic.backend.utils.NetworkUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, CaptchaInfo> redisTemplate;

    @Resource
    private CaptchaValidator captchaValidator;

    @Resource
    private CaptchaGenerator captchaGenerator;

    // region 参数校验方法
    private void validateRegisterParams(UserRegisterRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String[] fields = {
                request.getUserAccount(),
                request.getUserPassword(),
                request.getCheckPassword(),
                request.getUserPhoneNumber()
        };

        if (StringUtils.isAnyBlank(fields)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "所有字段必须填写");
        }

        if (!request.getUserPassword().matches("^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码需至少8位且包含字母和数字");
        }
    }

    // region 登录相关

    @GetMapping("/captcha")
    @ApiOperation(value = "获取验证码", notes = "")
    public void getCaptcha(HttpServletRequest request,
                           HttpServletResponse response) throws IOException {
        String clientIP = NetworkUtils.getClientRealIP(request);
        captchaGenerator.generateCaptcha(clientIP, response);
    }

    @PostMapping("/register")
    @ApiOperation(value = "用户注册", notes = "")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest request,
                                           HttpServletRequest httpRequest) {
        captchaValidator.validateCaptcha(httpRequest, request.getCaptcha());
        validateRegisterParams(request);

        long result = userService.userRegister(
                request.getUserAccount(),
                request.getUserPassword(),
                request.getCheckPassword(),
                request.getUserPhoneNumber());

        return ResultUtils.success(result, null);
    }

    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest request,
                                               HttpServletRequest httpRequest,
                                               HttpServletResponse httpResponse) {
        captchaValidator.validateCaptcha(httpRequest, request.getCaptcha());

        LoginUserVO loginUserVO = userService.userLogin(
                request.getUserAccount(),
                request.getUserPassword(),
                httpRequest);
        StpUtil.login(loginUserVO.getId());
        String token = StpUtil.getTokenValue();
        // 将token设置到响应头
        httpResponse.setHeader("Authorization", token);

        SaSession session = StpUtil.getSession();
        session.set("userInfo", loginUserVO);
        // 返回结果不再包含token
        return ResultUtils.success(loginUserVO,token);
    }

    @PostMapping("/logout")
    @ApiOperation(value = "用户注销", notes = "")
    public BaseResponse<Boolean> userLogout() {
        StpUtil.logout();
        return ResultUtils.success(true, null);
    }

    @GetMapping("/get/login")
    @ApiOperation(value = "获取当前登录用户", notes = "")
    @SaCheckLogin
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        try {
            // 安全转换为 long 类型
            String token = request.getHeader("Authorization");
            long userId = userService.getUserIdByToken(request);
            User user = userService.getUserById(userId);
            return ResultUtils.success(userService.getLoginUserVO(user), token);
        } catch (NotLoginException | NumberFormatException e) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
    }

    @GetMapping("/sessionData")
    @ApiOperation(value = "获取session数据", notes = "")
    @SaCheckLogin
    public BaseResponse<SaSession> getSessionData(HttpServletRequest request) {
        try {
            // 安全转换为 long 类型
            String token = request.getHeader("Authorization");
            long userId = userService.getUserIdByToken(request);
            SaSession session = StpUtil.getSessionByLoginId(userId);
            return ResultUtils.success(session, token);
        } catch (NotLoginException | NumberFormatException e) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
    }

    // endregion

    // region 增删改查

    @PostMapping("/add")
    @ApiOperation(value = "创建用户", notes = "")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        String defaultPassword = "12345678a";
        String encryptPassword = DigestUtils.md5DigestAsHex((UserConstant.SALT + defaultPassword).getBytes());
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId(), StpUtil.getTokenValue());
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除用户", notes = "")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b, StpUtil.getTokenValue());
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新用户", notes = "")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true, StpUtil.getTokenValue());
    }

    @GetMapping("/get")
    @ApiOperation(value = "根据 id 获取用户", notes = "")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user, StpUtil.getTokenValue());
    }

    @GetMapping("/get/vo")
    @ApiOperation(value = "根据 id 获取包装类", notes = "")
    public BaseResponse<UserVO> getUserVOById(long id) {
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(userService.getUserVO(user), StpUtil.getTokenValue());
    }

    @PostMapping("/list/page")
    @ApiOperation(value = "分页获取用户列表", notes = "")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<User>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest) {
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getSize();
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        return ResultUtils.success(userPage, StpUtil.getTokenValue());
    }

    @PostMapping("/list/page/vo")
    @ApiOperation(value = "分页获取用户封装列表", notes = "")
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getSize();
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
        List<UserVO> userVO = userService.getUserVO(userPage.getRecords());
        userVOPage.setRecords(userVO);
        return ResultUtils.success(userVOPage, StpUtil.getTokenValue());
    }

    // endregion

    @PostMapping("/update/my")
    @ApiOperation(value = "更新个人信息", notes = "修改密码需提供旧密码，否则旧密码可不填")
    @SaCheckLogin
    public BaseResponse<Boolean> updateMyUser(
            @RequestBody @Validated UserUpdateMyRequest request,
            HttpServletRequest req
    ) {
        // 1. 校验请求参数
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        request.validate(); // 触发自定义校验

        String token = req.getHeader("Authorization");
        long userId = userService.getUserIdByToken(req);

        // 3. 仅当修改密码时验证旧密码
        if (StringUtils.isNotBlank(request.getNewPassword())) {
            validateOldPassword(userId, request.getOldPassword());
        }

        // 4. 更新用户信息
        User user = buildUpdateUser(request, userId);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true,token);
    }

    // 辅助方法：验证旧密码
    private void validateOldPassword(long userId, String oldPassword) {
        User currentUser = userService.getUserById(userId);
        String encryptedOld = DigestUtils.md5DigestAsHex((UserConstant.SALT + oldPassword).getBytes());
        if (!currentUser.getUserPassword().equals(encryptedOld)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "旧密码错误");
        }
    }

    // 辅助方法：构建更新对象（避免覆盖未修改字段）
    private User buildUpdateUser(UserUpdateMyRequest request, long userId) {
        User user = new User();
        BeanUtils.copyProperties(request, user, "oldPassword", "newPassword"); // 排除密码字段
        user.setId(userId);

        // 仅当有新密码时更新
        if (StringUtils.isNotBlank(request.getNewPassword())) {
            String encryptedNew = DigestUtils.md5DigestAsHex(
                    (UserConstant.SALT + request.getNewPassword()).getBytes()
            );
            user.setUserPassword(encryptedNew);
        }
        return user;
    }
}